<template>
	<div ref="printArea">
		<el-card class="mb20">
			<div class="section-title">基础信息</div>
			<el-table :data="[baseInfo?.Entity]" v-if="baseInfo" class="unified-table">
				<el-table-column prop="photo" label="照片" width="120">
					<template #default="scope">
						<div class="photo-container">
							<img
								v-if="baseInfo.Entity.PhotoId"
								:src="`/api/_file/getfile/${baseInfo.Entity.PhotoId}?width=80&height=100`"
								alt="照片"
								class="person-photo"
								@load="onImageLoad"
								@error="onImageError"
							/>
							<div v-else class="no-photo">无照片</div>
						</div>
					</template>
				</el-table-column>
				<el-table-column prop="Name" label="姓名" />
				<el-table-column prop="StaffNo" label="工号" />
				<el-table-column prop="Gender" label="性别" />
				<el-table-column prop="BirthDate" label="出生日期" />
				<el-table-column prop="IdCardNo" label="身份证号" width="180" show-overflow-tooltip />
				<el-table-column prop="Age" label="年龄" />
				<el-table-column prop="Nation" label="民族" />
				<el-table-column prop="MaritalStatus" label="婚姻状况" />
				<el-table-column prop="IsVeteran" label="是否退伍军人">
					<template #default="scope">
						{{ scope.row.IsVeteran ? '是' : '否' }}
					</template>
				</el-table-column>
				<el-table-column prop="EducationLevel" label="最高学历" />
			</el-table>
		</el-card>

		<el-card class="mb20">
			<div class="section-title">学习经历</div>
			<el-table :data="educations" v-if="educations.length" class="unified-table">
				<el-table-column prop="PersonName" label="员工" />
				<el-table-column prop="School" label="学校" />
				<el-table-column prop="Major" label="专业" />
				<el-table-column prop="EducationLevel" label="学历" />
				<el-table-column prop="EducationSystem" label="学制" />
				<el-table-column prop="EnrollmentDate" label="入学日期" />
				<el-table-column prop="GraduationDate" label="毕业日期" />
			</el-table>
			<div v-else>无数据</div>
		</el-card>

		<el-card class="mb20">
			<div class="section-title">家庭成员</div>
			<el-table :data="families" v-if="families.length" class="unified-table">
				<el-table-column prop="PersonName" label="员工" />
				<el-table-column prop="MemberName" label="家属姓名" />
				<el-table-column prop="Relation" label="关系" />
				<el-table-column prop="Gender" label="性别" />
				<el-table-column prop="BirthDate" label="出生日期" />
				<el-table-column prop="PoliticalStatus" label="政治面貌" />
				<el-table-column prop="WorkOrSchool" label="工作单位/就读学校" />
				<el-table-column prop="Position" label="职务" />
				<el-table-column prop="Phone" label="联系电话" />
			</el-table>
			<div v-else>无数据</div>
		</el-card>

		<el-card class="mb20">
			<div class="section-title">工作经历</div>
			<el-table :data="works" v-if="works.length" class="unified-table">
				<el-table-column prop="PersonName" label="员工" />
				<el-table-column prop="Company" label="工作单位" />
				<el-table-column prop="Department" label="部门" />
				<el-table-column prop="Position" label="职务" />
				<el-table-column prop="StartDate" label="开始日期" />
				<el-table-column prop="EndDate" label="结束日期" />
			</el-table>
			<div v-else>无数据</div>
		</el-card>

		<el-card class="mb20">
			<div class="section-title">培训考试</div>
			<el-table :data="trainExams" v-if="trainExams.length" class="unified-table">
				<el-table-column prop="PersonName" label="员工" />
				<el-table-column prop="PersonTrainBatchName" label="培训批次" />
				<el-table-column prop="Score" label="成绩" />
			</el-table>
			<div v-else>无数据</div>
		</el-card>

		<el-card class="mb20">
			<div class="section-title">员工体检</div>
			<el-table :data="medicals" v-if="medicals.length" class="unified-table">
				<el-table-column prop="PersonName" label="员工" />
				<el-table-column prop="CheckDate" label="体检日期" />
				<el-table-column prop="Hospital" label="体检医院" />
				<el-table-column prop="Result" label="体检结果" />
			</el-table>
			<div v-else>无数据</div>
		</el-card>

		<el-card class="mb20">
			<div class="section-title">员工履历</div>
			<el-table :data="resumes" v-if="resumes.length" class="unified-table">
				<el-table-column prop="PersonName" label="员工" />
				<el-table-column prop="ResumeType" label="履历类型" />
				<el-table-column prop="OriginalGroupName" label="原部门" />
				<el-table-column prop="OriginalPositionName" label="原岗位" />
				<el-table-column prop="NewGroupName" label="新部门" />
				<el-table-column prop="NewPositionName" label="新岗位" />
				<el-table-column prop="ChangeDate" label="变动日期" />
			</el-table>
			<div v-else>无数据</div>
		</el-card>

		<el-card class="mb20">
			<div class="section-title">员工合同</div>
			<el-table :data="contracts" v-if="contracts.length" class="unified-table">
				<el-table-column prop="PersonName" label="员工" />
				<el-table-column prop="EmploymentType" label="用工形式" />
				<el-table-column prop="ContractType" label="合同类型" />
				<el-table-column prop="ContractNo" label="合同编号" />
				<el-table-column prop="SignDate" label="签订日期" />
				<el-table-column prop="ExpireDate" label="到期日期" />
				<el-table-column prop="ContractCount" label="合同次数" />
			</el-table>
			<div v-else>无数据</div>
		</el-card>

		<el-card class="mb20">
			<div class="section-title">员工荣誉</div>
			<el-table :data="titles" v-if="titles.length" class="unified-table">
				<el-table-column prop="PersonName" label="员工" />
				<el-table-column prop="ProfessionalTitleTypeName" label="资质类别" />
				<el-table-column prop="QualificationName" label="资质名称" />
				<el-table-column prop="QualificationLevel" label="资质等级" />
				<el-table-column prop="IssuingAuthority" label="发证单位" />
				<el-table-column prop="CertificateCode" label="证书编号" />
				<el-table-column prop="ObtainedDate" label="获得日期" />
				<el-table-column prop="ExpiryDate" label="有效期" />
				<el-table-column prop="SalaryReward" label="薪酬奖励" />
			</el-table>
			<div v-else>无数据</div>
		</el-card>
	</div>
</template>

<script setup lang="ts">
import { ref, onMounted, defineProps } from 'vue';
import { ElMessage } from 'element-plus';
import { SysPersonApi } from '../../views/person/sysperson/api';
import { SysPersonEducationApi } from '../../views/person/syspersoneducation/api';
import { SysPersonFamilyApi } from '../../views/person/syspersonfamily/api';
import { SysPersonWorkApi } from '../../views/person/syspersonwork/api';
import { SysPersonTrainExamApi } from '../../views/person/syspersontrainexam/api';
import { SysPersonMedicalApi } from '../../views/person/syspersonmedical/api';
import { SysPersonResumeApi } from '../../views/person/syspersonresume/api';
import { SysPersonContractApi } from '../../views/person/syspersoncontract/api';
import { SysPersonProfessionalTitleApi } from '../../views/person/syspersonprofessionaltitle/api';
import printJs from 'print-js';

const props = defineProps<{ personId: string }>();
const printArea = ref<HTMLElement | null>(null);

const baseInfo = ref<any>(null);
const educations = ref<any[]>([]);
const families = ref<any[]>([]);
const works = ref<any[]>([]);
const trainExams = ref<any[]>([]);
const medicals = ref<any[]>([]);
const resumes = ref<any[]>([]);
const contracts = ref<any[]>([]);
const titles = ref<any[]>([]);
const loading = ref(false);

async function fetchAllData() {
	try {
		loading.value = true;
		// 基础信息
		const personApi = SysPersonApi();
		const base = await personApi.get(props.personId);
		baseInfo.value = base;
		// 学习经历
		const educationApi = SysPersonEducationApi();
		const eduRes = (await educationApi.search({ PersonId: props.personId, Page: 1, PageSize: 100 })) as any;
		educations.value = eduRes.Data || [];
		// 家庭成员
		const familyApi = SysPersonFamilyApi();
		const famRes = (await familyApi.search({ PersonId: props.personId, Page: 1, PageSize: 100 })) as any;
		families.value = famRes.Data || [];
		// 工作经历
		const workApi = SysPersonWorkApi();
		const workRes = (await workApi.search({ PersonId: props.personId, Page: 1, PageSize: 100 })) as any;
		works.value = workRes.Data || [];
		// 培训考试
		const trainExamApi = SysPersonTrainExamApi();
		const trainExamRes = (await trainExamApi.search({ PersonId: props.personId, Page: 1, PageSize: 100 })) as any;
		trainExams.value = trainExamRes.Data || [];
		// 员工体检
		const medicalApi = SysPersonMedicalApi();
		const medicalRes = (await medicalApi.search({ PersonId: props.personId, Page: 1, PageSize: 100 })) as any;
		medicals.value = medicalRes.Data || [];
		// 员工履历
		const resumeApi = SysPersonResumeApi();
		const resumeRes = (await resumeApi.search({ PersonId: props.personId, Page: 1, PageSize: 100 })) as any;
		resumes.value = resumeRes.Data || [];
		// 员工合同
		const contractApi = SysPersonContractApi();
		const contractRes = (await contractApi.search({ PersonId: props.personId, Page: 1, PageSize: 100 })) as any;
		contracts.value = contractRes.Data || [];
		// 员工荣誉
		const titleApi = SysPersonProfessionalTitleApi();
		const titleRes = (await titleApi.search({ PersonId: props.personId, Page: 1, PageSize: 100 })) as any;
		titles.value = titleRes.Data || [];
	} catch (e) {
		ElMessage.error('加载打印数据失败');
	} finally {
		loading.value = false;
	}
}

// 图片加载处理
const onImageLoad = (event: Event) => {
	const img = event.target as HTMLImageElement;
	img.style.opacity = '1';
};

const onImageError = (event: Event) => {
	const img = event.target as HTMLImageElement;
	img.style.display = 'none';
	const container = img.parentElement;
	if (container) {
		container.innerHTML = '<div class="no-photo">加载失败</div>';
	}
};

onMounted(() => {
	fetchAllData().then(() => {});
});

// 打印方法（合并所有模块为一个大表格）
function handlePrint() {
	if (!baseInfo.value) return;

	const printTables = [];

	// 基础信息表格
	const base = baseInfo.value.Entity;
	const baseRows = [
		{
			姓名: base.Name || '',
			工号: base.StaffNo || '',
			性别: base.Gender || '',
			出生日期: base.BirthDate || '',
			身份证号: base.IdCardNo || '',
			年龄: base.Age || '',
			民族: base.Nation || '',
			婚姻状况: base.MaritalStatus || '',
			是否退伍军人: base.IsVeteran ? '是' : '否',
			最高学历: base.EducationLevel || '',
			照片: base.PhotoId ? `/api/_file/getfile/${base.PhotoId}?width=80&height=100` : '',
		},
	];
	const baseProps = Object.keys(baseRows[0]).map((key) => ({ field: key, displayName: key }));
	printTables.push({
		title: '基础信息',
		rows: baseRows,
		props: baseProps,
	});

	// 学习经历
	if (educations.value.length) {
		const eduRows = educations.value.map((e) => ({
			员工: e.PersonName || '',
			学校: e.School || '',
			专业: e.Major || '',
			学历: e.EducationLevel || '',
			学制: e.EducationSystem || '',
			入学日期: e.EnrollmentDate || '',
			毕业日期: e.GraduationDate || '',
		}));
		const eduProps = Object.keys(eduRows[0]).map((key) => ({ field: key, displayName: key }));
		printTables.push({ title: '学习经历', rows: eduRows, props: eduProps });
	}

	// 家庭成员
	if (families.value.length) {
		const famRows = families.value.map((f) => ({
			员工: f.PersonName || '',
			家属姓名: f.MemberName || '',
			关系: f.Relation || '',
			性别: f.Gender || '',
			出生日期: f.BirthDate || '',
			政治面貌: f.PoliticalStatus || '',
			工作单位或学校: f.WorkOrSchool || '',
			职务: f.Position || '',
			联系电话: f.Phone || '',
		}));
		const famProps = Object.keys(famRows[0]).map((key) => ({ field: key, displayName: key }));
		printTables.push({ title: '家庭成员', rows: famRows, props: famProps });
	}

	// 工作经历
	if (works.value.length) {
		const workRows = works.value.map((w) => ({
			员工: w.PersonName || '',
			工作单位: w.Company || '',
			部门: w.Department || '',
			职务: w.Position || '',
			开始日期: w.StartDate || '',
			结束日期: w.EndDate || '',
		}));
		const workProps = Object.keys(workRows[0]).map((key) => ({ field: key, displayName: key }));
		printTables.push({ title: '工作经历', rows: workRows, props: workProps });
	}

	// 培训考试
	if (trainExams.value.length) {
		const trainRows = trainExams.value.map((t) => ({
			员工: t.PersonName || '',
			培训批次: t.PersonTrainBatchName || '',
			成绩: t.Score || '',
		}));
		const trainProps = Object.keys(trainRows[0]).map((key) => ({ field: key, displayName: key }));
		printTables.push({ title: '培训考试', rows: trainRows, props: trainProps });
	}

	// 体检
	if (medicals.value.length) {
		const medRows = medicals.value.map((m) => ({
			员工: m.PersonName || '',
			体检日期: m.CheckDate || '',
			体检医院: m.Hospital || '',
			体检结果: m.Result || '',
		}));
		const medProps = Object.keys(medRows[0]).map((key) => ({ field: key, displayName: key }));
		printTables.push({ title: '员工体检', rows: medRows, props: medProps });
	}

	// 履历
	if (resumes.value.length) {
		const resumeRows = resumes.value.map((r) => ({
			员工: r.PersonName || '',
			履历类型: r.ResumeType || '',
			原部门: r.OriginalGroupName || '',
			原岗位: r.OriginalPositionName || '',
			新部门: r.NewGroupName || '',
			新岗位: r.NewPositionName || '',
			变动日期: r.ChangeDate || '',
		}));
		const resumeProps = Object.keys(resumeRows[0]).map((key) => ({ field: key, displayName: key }));
		printTables.push({ title: '员工履历', rows: resumeRows, props: resumeProps });
	}

	// 合同
	if (contracts.value.length) {
		const contractRows = contracts.value.map((c) => ({
			员工: c.PersonName || '',
			用工形式: c.EmploymentType || '',
			合同类型: c.ContractType || '',
			合同编号: c.ContractNo || '',
			签订日期: c.SignDate || '',
			到期日期: c.ExpireDate || '',
			合同次数: c.ContractCount || '',
		}));
		const contractProps = Object.keys(contractRows[0]).map((key) => ({ field: key, displayName: key }));
		printTables.push({ title: '员工合同', rows: contractRows, props: contractProps });
	}

	// 荣誉
	if (titles.value.length) {
		const titleRows = titles.value.map((t) => ({
			员工: t.PersonName || '',
			资质类别: t.ProfessionalTitleTypeName || '',
			资质名称: t.QualificationName || '',
			资质等级: t.QualificationLevel || '',
			发证单位: t.IssuingAuthority || '',
			证书编号: t.CertificateCode || '',
			获得日期: t.ObtainedDate || '',
			有效期: t.ExpiryDate || '',
			薪酬奖励: t.SalaryReward || '',
		}));
		const titleProps = Object.keys(titleRows[0]).map((key) => ({ field: key, displayName: key }));
		printTables.push({ title: '员工荣誉', rows: titleRows, props: titleProps });
	}

	// 组装HTML
	let html = '';
	function genTableHtml(title: string, rows: any[], props: { field: string; displayName: string }[]) {
		let table = `<div style='margin-bottom:12px;'><div style='font-weight:bold;font-size:14px;margin-bottom:4px;'>${title}</div><table><thead><tr>`;
		for (const p of props) table += `<th>${p.displayName}</th>`;
		table += '</tr></thead><tbody>';
		for (const row of rows) {
			table += '<tr>';
			for (const p of props) {
				if (title === '基础信息' && p.field === '照片' && row[p.field]) {
					table += `<td><img src='${row[p.field]}' style='width:60px;height:80px;object-fit:cover;border:1px solid #eee;border-radius:3px;'/></td>`;
				} else {
					table += `<td>${row[p.field] ?? ''}</td>`;
				}
			}
			table += '</tr>';
		}
		table += '</tbody></table></div>';
		return table;
	}
	for (const table of printTables) {
		html += genTableHtml(table.title, table.rows, table.props);
	}

	printJs({
		documentTitle: '人员信息打印',
		printable: html,
		type: 'raw-html',
		style: `@page { size: A4; }
		table { width: 100%; border-collapse: collapse; }
		th, td { border: 1px solid #ccc; padding: 4px; text-align: left; font-size: 12px; line-height: 1.2; }
		th { background-color: #f5f7fa; font-weight: bold; height: 24px; }
		td { height: 22px; }
		img { display: block; }
		`,
	});
}

defineExpose({ handlePrint });
</script>

<style scoped>
.section-title {
	font-size: 16px;
	font-weight: bold;
	margin-bottom: 10px;
}
.mb20 {
	margin-bottom: 20px;
}

/* 统一表格样式 */
.unified-table {
	border: 1px solid #ebeef5;
	border-radius: 4px;
}

.unified-table :deep(.el-table__header) {
	background-color: #f5f7fa;
}

.unified-table :deep(.el-table__header th) {
	background-color: #f5f7fa;
	color: #606266;
	font-weight: 600;
	border-bottom: 1px solid #ebeef5;
	padding: 12px 0;
}

.unified-table :deep(.el-table__body td) {
	border-bottom: 1px solid #ebeef5;
	padding: 12px 0;
	color: #606266;
}

.unified-table :deep(.el-table__body tr:hover) {
	background-color: #f5f7fa;
}

.unified-table :deep(.el-table__body tr:last-child td) {
	border-bottom: none;
}

/* 照片样式 */
.person-photo {
	width: 80px;
	height: 100px;
	object-fit: cover;
	border: 1px solid #eee;
	border-radius: 4px;
}

.photo-container {
	display: flex;
	align-items: center;
	justify-content: center;
}

.no-photo {
	width: 80px;
	height: 100px;
	border: 1px solid #eee;
	border-radius: 4px;
	display: flex;
	align-items: center;
	justify-content: center;
	color: #999;
	font-size: 12px;
	background-color: #f9f9f9;
}
</style>
